//
//  TeachPrivateClassViewController.m
//  fitnessmanage
//
//  Created by wujian on 2018/1/24.
//  Copyright © 2018年 zongquankeji. All rights reserved.
//  排私教

#import "TeachPrivateClassViewController.h"
#import "TeachPrivateClassHeadView.h"
#import "TeachClassPrivateTableViewCell.h"
#import "SelectWorkViewController.h"
#import "PrivateListViewController.h"


@interface TeachPrivateClassViewController ()<UITableViewDataSource,UITableViewDelegate>{
    
    int startIndex;
    
    int pageSize;
}

@property(nonatomic,weak)TeachPrivateClassHeadView *teachClassHeadView;

@property(nonatomic,weak)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataSource;

@property(nonatomic,strong)NoDataView *noDataView;

@property(nonatomic,weak)UIButton *functionBtn;

@end

@implementation TeachPrivateClassViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
 
    self.title = @"私教";
    
    self.view.backgroundColor = BackGroundColor;
    
    [self createSubView];
    
    [NotificationCenter addObserver:self selector:@selector(setSelectData:) name:@"selectDate" object:nil];
    
    [NotificationCenter addObserver:self selector:@selector(loadStartData) name:@"reloadPrivateTeach" object:nil];
}

-(void)createSubView{
    
    TeachPrivateClassHeadView *teachClassHeadView = [[TeachPrivateClassHeadView alloc] init];
    
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
    
    [format setDateFormat:@"yyyy-MM-dd"];
    
    self.date = [format stringFromDate:[NSDate date]];
    
    [teachClassHeadView.timeBtn setTitle:self.date];
    
    teachClassHeadView.startDate = self.date;
    
    [self.view addSubview:teachClassHeadView];
    
    self.teachClassHeadView = teachClassHeadView;

    [teachClassHeadView mas_remakeConstraints:^(MASConstraintMaker *make) {

        make.top.left.width.mas_equalTo(self.view);
    }];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.showsVerticalScrollIndicator = NO;
    tableView.estimatedRowHeight = 200;
    [tableView registerClass:[TeachClassPrivateTableViewCell class] forCellReuseIdentifier:@"TeachClassPrivateTableViewCell"];
    tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    tableView.backgroundColor = CSClearColor;
    [self.view addSubview:tableView];
    self.tableView = tableView;
    [tableView mas_remakeConstraints:^(MASConstraintMaker *make) {

        make.top.mas_equalTo(teachClassHeadView.mas_bottom).offset(10);

        make.left.width.bottom.mas_equalTo(self.view);
    }];

    UIButton *functionBtn = [[UIButton alloc] init];
    [functionBtn setImage:@"icn_add_course"];
    [functionBtn addTarget:self action:@selector(functionBtnClick)];
    [self.view addSubview:functionBtn];
    [functionBtn mas_remakeConstraints:^(MASConstraintMaker *make) {

        make.right.mas_equalTo(self.view).offset(-10);

        make.bottom.mas_equalTo(self.view).offset(-30);
    }];
    self.functionBtn = functionBtn;

    if ([self.type isEqualToString:@"Appoint"]) {
        
        functionBtn.hidden = YES;
    }
    
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    footer.automaticallyHidden = YES;
    
    
    MyTableHead *mj_head = [MyTableHead headerWithRefreshingTarget:self refreshingAction:@selector(loadStartData)];
    tableView.mj_header = mj_head;
    tableView.mj_footer = footer;
    [tableView.mj_header beginRefreshing];
    
}

#pragma mark 下拉
-(void)loadStartData{
    
    startIndex = 1;
    
    pageSize = 20;
    
    [self loadData];
}

#pragma mark 上拉
-(void)loadMoreData{
    
    startIndex = startIndex + 1;
    
    [self loadData];
}

/**
 加载数据
 */
-(void)loadData{
    
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    
    [MBProgressHUD showMessage:@"加载中..." toView:self.view];
    
    VenueModel *venueModel = [VenueModel venue];
    
    [params setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"ShopID"] forKey:@"ShopID"];
    
    [params setObject:self.date forKey:@"Date"];
    
    [params setObject:[NSString stringWithFormat:@"%d",startIndex] forKey:@"page"];
    
    [params setObject:[NSString stringWithFormat:@"%d",pageSize] forKey:@"rows"];
    
    [HTTPTool GET:GET_CoursePlanPrivateListByDate parameters:params
     
          success:^(id responseObject){
              
              [MBProgressHUD hideHUDForView:self.view];
              
              if (responseObject && [[responseObject objectForKey:@"Code"] intValue] == 0) {
                  
                  NSMutableArray *resultArray = [responseObject objectForKey:@"rows"];
                  
                  if (resultArray.count > 0) {
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshing];
                  }
                  else{
                      
                      [self.tableView.mj_header endRefreshing];
                      
                      [self.tableView.mj_footer endRefreshingWithNoMoreData];
                  }
                  
                  self.noDataView = [NoDataView shareInstance];
                  
                  [self.noDataView hideInView:self.view];
                  
                  if (startIndex == 1) {
                      
                      self.dataSource = [NSMutableArray arrayWithArray:resultArray];
                      
                      if (self.dataSource.count == 0) {
                          
                          self.noDataView = [NoDataView shareInstance];
                          
                          [self.noDataView showInView:self.view];
                      }
                  }
                  else{
                      
                      [self.dataSource addObjectsFromArray:resultArray];
                  }
                  
                  [self.tableView reloadData];
              }
              
          }
     
          failure:^(NSError *error){
              
              [self.tableView.mj_header endRefreshing];
              
              [MBProgressHUD hideHUDForView:self.view];
          }];
}

#pragma mark 设置 SelectDate
-(void)setSelectData:(NSNotification *)sender{
    
    NSDictionary *dict = sender.userInfo;
    
    NSString *date = [dict objectForKey:@"selectDate"];
    
    self.date = date;
    
    [self loadStartData];
}



#pragma mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSource.count;
}

#pragma mark UITableViewDelegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return CGFLOAT_MIN;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    TeachClassPrivateTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TeachClassPrivateTableViewCell"];
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",[dict objectForKey:@"Pic"],mid_image];
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [cell.classImageView sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:PlaceHold];
//
    cell.classNameLabel.text = [dict objectForKey:@"TeachName"];
//
//    cell.placeNameLabel.text = [NSString stringWithFormat:@"上课场地：%@",[dict objectForKey:@"PlaceName"]];
//    
//    cell.teachLabel.text = [NSString stringWithFormat:@"讲课老师：%@",[dict objectForKey:@"TeacherName"]];
//    
    NSString *BeginDateTime = [NSString stringWithFormat:@"%@ %@",[dict objectForKey:@"BeginDate"],[dict objectForKey:@"BeginHour"]];
    
    cell.timeLabel.text = [NSString stringWithFormat:@"%@~%@",[dict objectForKey:@"BeginHour"],[dict objectForKey:@"EndHour"]];
    
    NSString *endTime = [NSString stringWithFormat:@"%@ %@",[dict objectForKey:@"BeginDate"],[dict objectForKey:@"EndHour"]];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    if ([self compareOneDay:BeginDateTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] > 0) {
        
        [cell.stateBtn setTitle:@"待上课"];
        [cell.stateBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        cell.stateBtn.backgroundColor = ButtonBackGroundColor;
    }
    else if([self compareOneDay:BeginDateTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] < 0 && [self compareOneDay:endTime withAnotherDay:[dateFormatter stringFromDate:[NSDate date]]] > 0){
        
        [cell.stateBtn setTitle:@"进行中"];
        [cell.stateBtn setTitleColor:CSColorFromRGB(0x0a0a0a)];
        cell.stateBtn.backgroundColor = ButtonBackGroundColor;
    }
    else{
        
        [cell.stateBtn setTitle:@"已完成"];
        [cell.stateBtn setTitleColor:CSWhiteColor];
        cell.stateBtn.backgroundColor = CSColorFromRGBA(0xbdbdbd, 0.8);
    }
    
    cell.countLabel.text = [NSString stringWithFormat:@"%@",[dict objectForKey:@"Orders"]];
    
    NSArray *PrivateCourseName = [NSArray arrayWithArray:[dict objectForKey:@"PrivateCourseName"]];
    
    
    cell.teachLabel.text = [NSString stringWithFormat:@"课程项目：%ld类",PrivateCourseName.count];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    PrivateListViewController *privateListVC = [[PrivateListViewController alloc] init];
    
    privateListVC.type = self.type;
    
    NSDictionary *dict = [self.dataSource objectAtIndex:indexPath.row];
    
    privateListVC.dict = [NSMutableDictionary dictionaryWithDictionary:dict];
    
    privateListVC.date = self.date;
    
    [self.navigationController pushViewController:privateListVC animated:YES];
}


-(int)compareOneDay:(NSString *)oneDay withAnotherDay:(NSString *)anotherDay
{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSDate *dateA = [dateFormatter dateFromString:oneDay];
    
    NSDate *dateB = [dateFormatter dateFromString:anotherDay];
    
    NSComparisonResult result = [dateA compare:dateB];
    
    //NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    
    if (result == NSOrderedDescending) {
        
        //NSLog(@"Date1  is in the future");
        
        return 1;
        
    }
    
    else if (result ==NSOrderedAscending){
        
        //NSLog(@"Date1 is in the past");
        
        return -1;
        
    }
    
    //NSLog(@"Both dates are the same");
    
    return 0;
    
}

#pragma mark 功能点击
-(void)functionBtnClick{
    
    SelectWorkViewController *selectWorkVC = [[SelectWorkViewController alloc] init];
    
    selectWorkVC.from = @"教练";
    
    [self.navigationController pushViewController:selectWorkVC animated:YES];
}


-(NSMutableArray *)dataSource{
    
    if (!_dataSource) {
        
        _dataSource = [[NSMutableArray alloc] init];
    }
    
    return _dataSource;
}

-(void)dealloc{
    
    [NotificationCenter removeObserver:self];
}

@end
